/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ai.tubes.iris.knowledge;

/**
 *
 * @author Archie
 */
import java.util.ArrayList;
import java.io.*;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ai.tubes.iris.helper.Utilities;

import android.util.Log;
public class inferenceengine {

    /***
     * Inference Table
     */
    private String[][] InferenceTable = new String[3][19];
    String filepath; //filepath tempat naro eksternal Filenya
    /***
     * Konstruktor
     */
    public inferenceengine() {
    	filepath =  Utilities.BASE_DIRECTORY + "/setting/log/";

		boolean exists = (new File(filepath).exists());

		if (!exists) {new File(filepath).mkdirs();}
		
		
    	if (!new File(filepath + "InfTable.izit").exists()) //jika file tidak ada, buat dulu
        {
            makeDefaultInferenceFile(2, 4);
        }
        readInferenceFile(); //baca inference file
    }
    
    
    /***
     * Getter untuk inferencetable
     * @return
     */
    public String[][] getInferenceTable()
    {return InferenceTable;}
    
    public void setInferenceTable(String[][] Tableinput)
    {InferenceTable = Tableinput;}

    /***
     * Membuat file learning yang default
     */
    private void makeDefaultLearningFile()
    {
        try {
            FileWriter fstream = new FileWriter(filepath + "LearningData.izit");
            BufferedWriter out = new BufferedWriter(fstream);
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    /***
     * Add learning data ke file
     * @param organ
     * @param tingkatKesehatan
     * @param data
     */
    public void addLearningData(String organ, String tingkatKesehatan, float data) {
    	if(! new File(filepath + "LearningData.izit").exists()) //jika belum ada, buat dulu
        {
            makeDefaultLearningFile();
        }
        try {
            FileOutputStream out = new FileOutputStream(new File(filepath + "LearningData.izit"), true);
            String str = organ + " " + tingkatKesehatan + " " + String.valueOf(data)+"\n";
            out.write(str.getBytes());
            out.close();
        } catch (IOException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }

    /***
     * Ambil learning data dari data eksternal
     * @param organ
     * @param tingkatKesehatan
     * @return
     */
    public float getLearningData(String organ,  String tingkatKesehatan) {
        try {
            String str;
            float totalNilai=0;
            int totalData=0;
            BufferedReader reader = new BufferedReader(new FileReader(filepath + "LearningData.izit"));
                while ((str = reader.readLine()) != null) {
                    if(!str.equals(""))
                    {

                    String Penampungtemporer[] = str.split(" ");
                    if((Penampungtemporer[0].equalsIgnoreCase(organ)) && (Penampungtemporer[1].equalsIgnoreCase(tingkatKesehatan)))
                    {totalNilai+= new Float(Penampungtemporer[2]) ;totalData++;}
                    
                    }
                }
            if(totalNilai==0)
                return 0;
            else
            {return (float) totalNilai/totalData;}
        } catch (Exception e) {
            System.out.print(e);
            return 0;
        }
    }
    
    /***
     * 
     * @param organ
     * @param batas 0 batas bawah, 1 batas atas
     * @return
     */
	public String SaranLearningData(String organ) {
		float temp1, temp2;
		String output = "";
		// batas bawah

		temp1 = getLearningData(organ, "Lemah");
		temp2 = getLearningData(organ, "Sedang");
		if ((temp1 == 0) && (temp2 == 0)) {
			output+= "Batas Bawah : Data learning belum cukup\n";

		} else {
			output+= "Batas Bawah : " + String.valueOf(((temp1 + temp2) / 2))
					+ "\n";

		}
		// batas atas

		temp1 = getLearningData(organ, "Sedang");
		temp2 = getLearningData(organ, "Baik");
		if ((temp1 == 0) && (temp2 == 0)) {
			output+= "Batas Atas : Data learning belum cukup\n";

		} else {
			output+= "Batas Atas : " + String.valueOf(((temp1 + temp2) / 2))
					+ "\n";

		}
		
		return output;

	}

    public String InferenceStatus(String organ, float nilai) {
        for (int i = 0; i < 19; i++) {
            if (InferenceTable[0][i].equalsIgnoreCase(organ)) //jika nama organ ketemu
            {
                if (nilai < new Float(InferenceTable[1][i])) //jika lebih kecil modal awal, buruk
                {
                	addLearningData(organ, "Lemah", nilai);
                    return "Lemah";
                } else if (nilai < new Float(InferenceTable[2][i])) //jika lebih kecil modal awal, buruk
                {
                	addLearningData(organ, "Sedang", nilai);
                    return "Sedang";
                } else {
                	addLearningData(organ, "Baik", nilai);
                    return "Baik";
                }
            }
        }
        return "Data tidak ada";
    }

    public void changeInferenceStatus(String organ, float nilaibawah,float nilaiatas)
    {
        for (int i = 0; i < 19; i++) {
            if (InferenceTable[0][i].equalsIgnoreCase(organ)) //jika nama organ ketemu
            {
                InferenceTable[1][i] = String.valueOf(nilaibawah);
                InferenceTable[2][i] = String.valueOf(nilaiatas);
            }
        }
    }

    public void readInferenceFile() {
        try {
            String str = new String();
            BufferedReader reader = new BufferedReader(new FileReader(filepath + "InfTable.izit"));
            for (int i = 0; i < 19; i++) {
                if ((str = reader.readLine()) != null) {
                    String Penampungtemporer[] = str.split(" ");
                    InferenceTable[0][i] = Penampungtemporer[0];
                    InferenceTable[1][i] = Penampungtemporer[1];
                    InferenceTable[2][i] = Penampungtemporer[2];
                }

            }
        } catch (Exception e) {
            System.out.print(e);
        }
    }

    public void  writeInferenceFile() {
        try {
            FileWriter fstream = new FileWriter(filepath + "InfTable.izit");
            BufferedWriter out = new BufferedWriter(fstream);
            for (int i = 0; i < 19; i++) {
                if (i >= 18) //yang ujung ga usah pake enter
                {
                    out.write(InferenceTable[0][i] + " " + InferenceTable[1][i] + " " + InferenceTable[2][i]);
                } else {
                    out.write(InferenceTable[0][i] + " " + InferenceTable[1][i] + " " + InferenceTable[2][i] + "\n");
                }
            }
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }

    public void makeDefaultInferenceFile(int batasbawah, int batasatas) {
        try {
            FileWriter fstream = new FileWriter(filepath + "InfTable.izit");
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("Laring " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Tiroid " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Bronkus " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Appendix " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Pankreas " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Hati " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Empedu " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Ginjal " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("RonggaDada " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Paruparu " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Bronchialis " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Jantung " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Limpa " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("KolonMenaik " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("KolonMenurun " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("UsusKecil " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("KolonSigmoid " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("UsusBuntu " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas) + "\n");
            out.write("Lambung " + String.valueOf(batasbawah) + " " + String.valueOf(batasatas));
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
    
    public void serverUpdate () {
    	String result = "";
    	
    	ArrayList < NameValuePair > request = new ArrayList < NameValuePair >();
    	request.add(new BasicNameValuePair("update", "ambang"));
    	
    	/* HTTP POST request */
	    	try {
	    		HttpClient httpClient = new DefaultHttpClient();
	    		HttpPost httpPost = new HttpPost("http://k-1cafe.com/update.php");
	    		httpPost.setEntity(new UrlEncodedFormEntity(request));
	    		HttpResponse response = httpClient.execute(httpPost);
	    		HttpEntity entity = response.getEntity();
	    		InputStream instream = entity.getContent();
	    		
	    		/* HTTP POST response */
			    	//convert response to String
			    	try {
			    		BufferedReader buffreadr = new BufferedReader(new InputStreamReader(instream, "iso-8859-1"), 8);
			    		StringBuilder strbuildr = new StringBuilder();
			    		String line = null;
			    		
			    		while ((line = buffreadr.readLine()) != null) {
			    			strbuildr.append(line + "\n");
			    		}
			    		
			    		instream.close();
			    		
			    		result = strbuildr.toString();
			    		
			    		//parse JSON data
			    		try {
			    			JSONArray jArray = new JSONArray(result);
			    			for (int i = 0; i < jArray.length(); ++i) {
			    				JSONObject data = jArray.getJSONObject(i);
			    				/* ///@todolist : implements data use */
			    				changeInferenceStatus(data.getString("label"), Float.parseFloat(data.getString("bawah")), Float.parseFloat(data.getString("atas")));
			    			}
			    			writeInferenceFile();
			    		} catch (JSONException e) {
			    			Log.e("log_tag", "Error parsing data " + e.toString());
						}
			    	} catch (Exception e) {
			    		Log.e("log_tag", "Error converting result " + e.toString());
					}
			    	
	    	} catch (Exception e) {
				Log.e("log_tag", "Error in HTTP connection " + e.toString());
			}
    }
}
